package cn.gqr.dao;

import cn.gqr.entity.User;
import cn.gqr.uitl.SessionUitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Repository;

@Repository
public class UserDao {

    @Autowired
    MongoTemplate mT;

    @Autowired
    BCryptPasswordEncoder bcry;

    //查找账号
    public User findByUsername(String username){
        Criteria c = new Criteria();
        User user = mT.findOne(new Query(c.where("username").is(username)), User.class);
        return user;
    }

    //根据id查找账号
    public User findById(String id){
        Criteria c = new Criteria();
        User user = mT.findOne(new Query(c.where("_id").is(id)),User.class);
        return user;
    }

    //注册
    public User addUser(User u){
        u.setRole("P");
        u.setPassword(bcry.encode(u.getPassword()));
        User usr = findByUsername(u.getUsername());
        if(usr!=null){
            return null;
        }
        User user = mT.insert(u);
        return user;
    }

    //修改用户信息
    public boolean upUser(User u){

        Query q = new Query();
        q.addCriteria(Criteria.where("id").is(u.getId()));
        Update up = new Update();
        if( u.getNickname().trim().length()>0 ){
            up.set("nickname",u.getNickname());
        }

        if( u.getBirthdate()!=null ){
            up.set("birthdate",u.getBirthdate());
        }

        if( u.getPhone().trim().length()>0 ){
            up.set("phone",u.getPhone());
        }

        if( u.getSex().trim().length()>0 ){
            up.set("sex",u.getSex());
        }

        boolean b = mT.updateFirst(q, up, User.class).wasAcknowledged();
        return  b;
    }

}
